<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>axios入门与源码解析</title>
  <link rel="stylesheet" href="../bootstrap.min.css">
  <script src="../axios.js"></script>
</head>

<body>
  <div class="container">
    <h2>axios基本使用</h2>
    <button class="btn btn-primary">发送GET请求</button>
    <button class="btn btn-warning">取消请求</button>
  </div>
  <script>
    // 获取按钮
    const btns = document.querySelectorAll('button')
    // 2、声明全局变量
    let cancel = null;
    // 发送请求
    btns[0].onclick = function(){
      if(cancel!==null){
        // 取消上一次请求
        cancel()
      }
      axios({
        method:'get',
        url:'http://localhost:3000/posts',
        // 1、添加配置对象的属性
        cancelToken: new axios.CancelToken(function(c){
          // 3、将c赋值给cancel
          cancel = c
        })
      }).then(res=>{
        console.log(res)
        // 将cancel的值初始化
        cancel = null
      })
    }
    btns[1].onclick = function(){
      cancel()
    }
  </script>
</body>

</html>